package top.fyukina.fymil.elements;

import top.fyukina.fymil.DataType;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

public class VarDomain {
    private final Map<String, Object> vars = new HashMap<>();
    public synchronized void saveVar(String varName, Object value) {
        if (vars.containsKey(varName)) {
            vars.replace(varName, value);
        } else {
            vars.put(varName, value);
        }
    }
    public synchronized boolean opVar(String varName, Function<Object, Object> operation) {
        Object var = getVar(varName, false);
        if (var == null) {
            return false;
        }
        saveVar(varName, operation.apply(var));
        return true;
    }
    public Object getVar(String varName) {
        return getVar(varName, true);
    }
    public Object getVar(String varName, boolean nonNull) {
        return vars.getOrDefault(varName, nonNull ? DataType.getDefaultNonType() : null);
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("VarDomain{\n");
        for (Map.Entry<String, Object> entry : vars.entrySet()) {
            sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append("\n");
        }
        return sb.append("}").toString();
    }
}